<?php

namespace pmvc\log;

use DateTime;

/**
 * Appender for appending to STDOUT.
 */
class ConsoleAppender
	implements Appender {

	private $formatter;
	private $stdout;
	private $stderr;

	/**
	 * Creates an appender that appends to the console
	 * using the given {@link Formatter} to format the
	 * log messages.
	 * 
	 * @param Formatter $formatter
	 */
	public function __construct(Formatter $formatter=null) {
		$this->formatter	= $formatter;
		$this->stdout		= fopen('php://stdout', 'w');
		$this->stderr		= fopen('php://stderr', 'w');
	}

	/**
	 * Destruction!
	 */
	public function __destruct() {
		fclose($this->stdout);
		fclose($this->stderr);
	}

	/**
	 * {@inheritDoc}
	 */
	public function append($level, DateTime $time, $name, $message) {
		$msg = $this->formatter->format($level, $time, $name, $message);
		if ($level>=Logger::WARN) {
			fwrite($this->stderr, $msg);
			flush($this->stderr);
		} else {
			fwrite($this->stdout, $msg);
			flush($this->stdout);
		}
	}

}

?>